import 'dart:io';

import 'package:flutter/material.dart';
import 'package:mvvm_demo/login_service.dart';

class LoginMVC extends StatefulWidget {
  const LoginMVC({Key? key}) : super(key: key);

  @override
  _LoginMVCState createState() {
    return _LoginMVCState();
  }
}

class _LoginMVCState extends State<LoginMVC> {
  bool isLogon = false;
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(top: 30, left: 15, right: 15),
        child: Column(
          children: [
            TextField(
              decoration: const InputDecoration(
                labelText: "账号",
                prefixIcon: Icon(Icons.person),
                hintText: "请输入账号",
              ),
              controller: _usernameController,
            ),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: "密码",
                prefixIcon: Icon(Icons.lock),
                hintText: "请输入密码",
              ),
            ),
            Container(
              color: Colors.red,
              margin: const EdgeInsets.only(top: 20),
              child: ElevatedButton(
                onPressed: () => isLogon ? _logout() : _login(),
                child: Text(isLogon ? "注销" : "登录"),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _login() async {
    String username = _usernameController.text;
    String password = _passwordController.text;
    isLogon = await LoginService.login(username, password);
    setState(() {});
  }

  _logout() async {
    bool result = await LoginService.logout();
    if (result) {
      isLogon = false;
    }
    setState(() {});
  }
}
